package org.taobao.ibatiside.ui.action;

import org.eclipse.datatools.connectivity.internal.ConnectionProfile;
import org.eclipse.datatools.modelbase.sql.schema.Schema;
import org.eclipse.datatools.modelbase.sql.tables.Table;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.navigator.CommonActionProvider;
import org.eclipse.ui.navigator.CommonViewer;
import org.eclipse.ui.navigator.ICommonActionExtensionSite;

public class DseViewActionProvider extends CommonActionProvider {
	private ISelectionProvider selectionProvider;
	private ConnectionToConfigurationAction c2c = new ConnectionToConfigurationAction();
	private DseBatchGenerateAction batch = new DseBatchGenerateAction();
	private DseNewDeleteAction delete = new DseNewDeleteAction();
	private DseNewInsertAction insert = new DseNewInsertAction();
	private DseNewSelectAction select = new DseNewSelectAction();
	private DseNewUpdateAction update = new DseNewUpdateAction();

	@Override
	public void init(ICommonActionExtensionSite aSite) {
		this.selectionProvider = aSite.getViewSite().getSelectionProvider();
		CommonViewer viewer = (CommonViewer) aSite.getStructuredViewer();
		c2c.initialize(viewer);
		batch.initialize(viewer);
		delete.initialize(viewer);
		insert.initialize(viewer);
		select.initialize(viewer);
		update.initialize(viewer);
	}

	@Override
	public void fillContextMenu(IMenuManager menu) {
		if (getContext().getSelection().isEmpty()
				|| !(getContext().getSelection() instanceof StructuredSelection)) {
			return;
		}
		StructuredSelection view_selection = (StructuredSelection) getContext()
				.getSelection();
		SelectionChangedEvent event = new SelectionChangedEvent(
				this.selectionProvider, getContext().getSelection());
		if (view_selection.size() == 1) {
			Object sqlobject = view_selection.getFirstElement();
			if (sqlobject instanceof Table) {
				delete.selectionChanged(event);
				insert.selectionChanged(event);
				select.selectionChanged(event);
				update.selectionChanged(event);
				menu.insertAfter("slot3", insert);
				menu.insertAfter("slot3",select);
				menu.insertAfter("slot3", update);
				menu.insertAfter("slot3", delete);
			}else if (sqlobject instanceof ConnectionProfile){
				c2c.selectionChanged(event);
				menu.insertAfter("slot3", c2c);
			}else if (sqlobject instanceof Schema){
				menu.insertAfter("slot3", batch);
			}
		} else {
			batch.selectionChanged(event);
			menu.insertAfter("slot3", batch);
		}
	}
}
